<template>
  <div>
    <van-swipe-cell
      v-for="item in cartList"
      :key="item.cartid"
      :name="item.cartid"
      :before-close="beforeClose"
      :stop-propagation="true"
    >
      <van-checkbox
        v-model="item.flag"
        icon-size="24px"
        @click="is_checked(item.flag)"
      ></van-checkbox>
      <van-card
        :price="item.originprice"
        :title="item.proname"
        class="goods-card"
        :thumb="item.img1"
        @click-thumb="jumpTo(item.proid)"
      >
        <template #footer>
          <van-stepper
            v-model="item.num"
            theme="round"
            button-size="22"
            disable-input
            @change.="updateNum1(item.cartid, item.num)"
          />
        </template>
      </van-card>
      <template #right>
        <van-button square text="删除" type="danger" class="delete-button" />
      </template>
    </van-swipe-cell>
    <submit :list="cartList"></submit>
  </div>
</template>

<script>
import Submit from "./submit.vue";
import Vue from "vue";
import {
  SwipeCell,
  Card,
  Checkbox,
  CheckboxGroup,
  Stepper,
  Dialog,
} from "vant";
import { getCart, updateNum, selectone, remove } from "../../apis/cart";

Vue.use(Card);
Vue.use(SwipeCell);
Vue.use(Checkbox);
Vue.use(CheckboxGroup);
Vue.use(Stepper);

export default {
  name: "CartList",
  components: {
    Submit,
  },
  data() {
    return {
      cartList: [],
    };
  },

  mounted() {},

  methods: {
    // 更新数量
    updateNum1(cartid, num) {
      updateNum({ cartid, num }).then();
    },

    // 单选
    is_checked(flag) {
      flag = !flag;
      selectone({ flag }).then();
    },

    // 单删
    beforeClose({ name, position, instance }) {
      switch (position) {
        case "right":
          Dialog.confirm({
            message: "亲，确定不要这个宝贝了吗？",
          })
            .then(() => {
              remove({ cartid: name }).then((data) => {
                if (data.data.code == 200) {
                  getCart({ userid: localStorage.getItem("userid") }).then(
                    (data) => {
                      // console.log(data.data.data);
                      this.cartList = data.data.data;
                    }
                  );
                }
              });
              instance.close();
            })
            .catch(() => {
              instance.close();
            });
          break;
      }
    },

    // 跳转详情
    jumpTo(proid) {
      this.$router.push("/pro/detail/" + proid);
    },
  },

  // 发请求的位置！！！
  created() {
    getCart({ userid: localStorage.getItem("userid") }).then((data) => {
      // console.log(data.data.data);
      this.cartList = data.data.data;
    });
  },
};
</script>

<style  scoped>
.goods-card {
  margin: 0;
  background-color: #fff;
}
.delete-button {
  height: 100%;
}
.van-card {
  flex: 1;
}
::v-deep .van-swipe-cell__wrapper {
  display: flex;
  background-color: #fff;
  margin-bottom: 0.1rem;
  padding: 0.1rem;
}
</style>